<template>
  <BasicDrawer @register="registerBaseDrawer" title="订阅的消息通知" width="700px" destroyOnClose>
    <BasicTable @register="registerTable">
      <template #tableTitle>
        <a-button type="primary" @click="handleSelect">订阅</a-button>
      </template>
      <template #action="{ record }">
        <TableAction :actions="getTableAction(record)" />
      </template>
    </BasicTable>
  </BasicDrawer>
  <ReceiverSubscribeNotice @register="registerModal" @select="selectOk" />
</template>
<script lang="ts" setup>
  import { ref, watch, unref } from "vue"
  import { BasicTable, useTable, TableAction } from "/@/components/Table"
  import { BasicDrawer, useDrawer, useDrawerInner } from "/@/components/Drawer"
  import { useModal } from "/@/components/Modal"
  import { listSubscribeMsg } from "../receiver.api"
  import { deleteMsgSubscriber, saveMsgSubscriber } from "../../notice/api"
  import { receiverSubscribeColumns, searchUserFormSchema } from "../receiver.data"
  import ReceiverSubscribeNotice from "../../notice/components/ReceiverSubscribeNotice.vue"

  const emit = defineEmits(["register", "hideUserList"])
  const checkedKeys = ref<Array<string | number>>([])
  const receiverId = ref("")
  const [registerBaseDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
    receiverId.value = data.record.id
    setProps({ searchInfo: { receiverId: data.record.id } })
    reload()
  })

  const [registerModal, { openModal }] = useModal()
  const [registerTable, { reload, updateTableDataRecord, setProps }] = useTable({
    title: "接收人订阅的消息",
    api: listSubscribeMsg,
    columns: receiverSubscribeColumns,
    formConfig: {
      labelWidth: 60,
      schemas: searchUserFormSchema,
      showResetButton: false,
      showSubmitButton: false,
      autoSubmitOnEnter: true,
      labelCol: { lg: 8, md: 8 },
      actionColOptions: { lg: 6, md: 6 },
    },
    bordered: false,
    striped: true,
    useSearchForm: true,
    showTableSetting: true,
    clickToRowSelect: false,
    showIndexColumn: false,
    tableSetting: { fullScreen: true },
    canResize: false,
    rowKey: "id",
    immediate: false,
    actionColumn: {
      width: 50,
      title: "操作",
      dataIndex: "action",
      slots: { customRender: "action" },
      fixed: undefined,
    },
  })

  async function handleDelete(record) {
    await deleteMsgSubscriber({ receiverIds: [receiverId.value], noticeIds: [record.id], name: record.name }, reload)
  }

  function handleSelect() {
    openModal(true, {})
  }

  async function selectOk(val) {
    await saveMsgSubscriber({ noticeIds: val, receiverIds: [receiverId.value] })
    reload()
  }

  function getTableAction(record): any[] {
    return [
      {
        label: "移除",
        color: "error",
        onClick: handleDelete.bind(null, record),
      },
    ]
  }
</script>
